package com.jxau.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jxau.entity.Article;
import com.jxau.entity.Comment;
import com.jxau.entity.UserSession;
import com.jxau.util.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {
    private String[] unLoginUrl = {"getUser", "query", "find", "viewPlus", "login"};
    private String[] needLoginUrl = {"edit", "do","ollow","cleanRed",
            "getNewCommentAndLikeNum", "add"};
    private String[] needAdminUrl = {"page", "updateUser", "delete", "Top"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String url = request.getRequestURI();
        // 放行无需登录url
        for (String s : unLoginUrl) {
            if (url.contains(s)){
                return true;
            }
        }

        // 以下为需要登录拦截
        HttpSession session = request.getSession();
        UserSession user = (UserSession) session.getAttribute("user");
        if (user == null) {
            response.setStatus(401);
            return false;
        }
        // 禁止未登录操作有关用户数据或操作非本人相关数据
        String uidValue = request.getParameter("uid");
        for (String s : needLoginUrl) {
            if (url.contains(s)) {
                if (user.getId().equals(uidValue)) {
                    return true;
                } else {
                    response.setStatus(401);
                    return false;
                }
            }
        }
        // 需要管理员权限拦截
        for (String s : needAdminUrl) {
            if (url.contains(s)) {
                // 需要管理员权限
                if (user.getRole() == 1) {
                    // 有管理员权限
                    return true;
                } else {
                    // 无管理员权限
                    response.setStatus(401);
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
